package com.android.locationapi.maps;



import java.io.IOException;
import java.util.List;
import java.util.Locale;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Point;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;



public class authenticated extends MapActivity implements LocationListener{

    TextView		myLoc			= null;
	
	MapView			myMapView		= null;
	
	MapController	myMC			= null;
	
	GeoPoint		geoPoint		= null;
	
	static double			latitude		= 35.774291, longitude = -78.68358;
	
	String add = "";
	
	 Location location = null;
	
	 
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		setRequestedOrientation(1);
		super.onCreate(savedInstanceState);
		setContentView(R.layout.authenticated);
		
		// Creating TextBox displaying Latitude, Longitude
		myLoc = (TextView) findViewById(R.id.id1);
		
		
		// Creating and initializing Map
		myMapView = (MapView) findViewById(R.id.myGMap);
		geoPoint = new GeoPoint((int) (latitude * 1000000), (int) (longitude * 1000000));
		
	//	Log.v("bishon GEO",geoPoint.toString());
		myMapView.setSatellite(false);
		
		Thread t = new Thread() {
			public void run() {
				try {
					
	 
					
	 
					runOnUiThread(new Runnable() {
						public void run() {
							onMyCreate();
						}
					});
				} catch (Exception e) {}
			}
		};
		t.start();
		
		
		
	        
	       // Log.v("bishon: adddreeeessss","done");
	
	}
	
	public void onMyCreate ()
	{
	
		/*Geocoder geocoder = new Geocoder(getApplicationContext(), Locale.getDefault());
		 try {
			List<Address> addresses = geocoder.getFromLocation(
					 geoPoint.getLatitudeE6()  / 1E6, 
					 geoPoint.getLongitudeE6() / 1E6, 1);
		    
           if (addresses.size() > 0) 
           {
               for (int i=0; i<addresses.get(0).getMaxAddressLineIndex(); 
                    i++)
                  add += addresses.get(0).getAddressLine(i) + "\n";
           }
           
           Log.v("bishon:addressme-->", add);
           
           
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		*/
		
		String currentLocation = "Current Location: \n Latitude: " + latitude + "\n Longitude: " + longitude ;
		myLoc.setText(currentLocation);
		
		//Log.v ("bishon:before",geoPoint.toString());
		
		//Getting the MapController to fine tune settings
		myMC = myMapView.getController();
		myMC.setCenter(geoPoint);
		myMC.setZoom(15);
		
		// Add a location mark
		MyLocationOverlay myLocationOverlay = new MyLocationOverlay();
		List<Overlay> list = myMapView.getOverlays();
		list.add(myLocationOverlay);
		
		// Adding zoom controls to Map
		myMapView.setBuiltInZoomControls(true);
       myMapView.displayZoomControls(true);
				
		// Getting locationManager and reflecting changes over map if distance travel by
		// user is greater than 500m from current location.
       
       
       
		LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
		lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
		
		
		
		 Button addbtn = (Button)findViewById(R.id.addressbtn);
	        addbtn.setOnClickListener(new OnClickListener() 
	        {
	        	
	        	public void onClick(View v)
	        	{
	        		Intent explicitIntent = new Intent(authenticated.this,authenticated.class);
	        		Log.v("bishon","done 55");
	        		
	        		Bundle b = new Bundle();
	        		
	                b.putString("latitude", Double.toString(latitude));
	                b.putString("longitude", Double.toString(longitude));
	                
	                
	                explicitIntent.putExtras(b);  
	        		
	        		Log.v("bishon","done 77");
	                startService(explicitIntent);
	                Log.v("bishon","done 99");
	                
	                
	                
	                
	      
	        		
	        	}
	        });
	        
	        
	        Button newtag = (Button)findViewById(R.id.tags);
	        newtag.setOnClickListener(new OnClickListener() 
	        {
	        	
	        	public void onClick(View v)
	        	{
	        		//Intent explicitIntent1 = new Intent(authenticated.this,tagchoice.class);
	        		Intent explicitIntent1 = new Intent(authenticated.this,authenticated.class);
	        		Log.v("bishon","done 505");
	        		
	        		Bundle b = new Bundle();
	        		
	                b.putString("latitude", Double.toString(latitude));
	                b.putString("longitude", Double.toString(longitude));
	                
	                
	                explicitIntent1.putExtras(b);  
	        		
	        		
	        		Log.v("bishon","done 707");
	                startActivity(explicitIntent1);
	                Log.v("bishon","done 909");
	                
	                
	                
	                
	      
	        		
	        	}
	        });
	        
	        
	        Button frndbtn = (Button)findViewById(R.id.friends);
	        frndbtn.setOnClickListener(new OnClickListener() 
	        {
	        	
	        	public void onClick(View v)
	        	{
	        		Intent explicitIntent1 = new Intent(authenticated.this,authenticated.class);
	        		Log.v("bishon","done 505");
	        		
	        		Log.v("bishon","done 707");
	                startActivity(explicitIntent1);
	                Log.v("bishon","done 909");
	                
	                
	                
	                
	      
	        		
	        	}
	        });
	        
	        
	}
	
	public void onLocationChanged(final Location location) {
		
		Thread t = new Thread() {
			public void run() {
				try {
					
	 
					
	 
					runOnUiThread(new Runnable() {
						public void run() {
							onMyLocChanged(location);
						}
					});
				} catch (Exception e) {}
			}
		};
		t.start();
		
		
	}
	
	
	public void onMyLocChanged(Location location)
	{
		
		if (location != null) {
			 add = "";
			double  lat =  location.getLatitude();
			double  lng =  location.getLongitude();
			
			/*double lat = 35.771924;
				double lng= -78.673898; */	
			//int clat= (int)(lat*1000000);
			//int clng= (int)(lng*1000000);
			//System.out.println("lat"+clat);
			//System.out.println("lng"+clng);
				//Log.v("bishon : lat : ", Integer.toString((int)(lat*1000000)));
				//Log.v("bishon : lng :", Integer.toString((int)(lng*1000000)));
				
				
				
				
			String currentLocation = "Current Location: \n Latitude: " + lat + "\n Longitude: " + lng;
			myLoc.setText(currentLocation);
			geoPoint = new GeoPoint((int) (lat * 1000000), (int) (lng * 1000000));
			//Log.v ("bishon:after",geoPoint.toString());
			myMC.animateTo(geoPoint);
			
		}
		
	}
	
	public void onProviderDisabled(String provider) {
		// required for interface, not used
	}
	
	public void onProviderEnabled(String provider) {
		// required for interface, not used
	}
	
	public void onStatusChanged(String provider, int status, Bundle extras) {
		// required for interface, not used
	}
	
	protected boolean isRouteDisplayed() {
		return false;
	}
	
	
	public boolean onKeyDown(int keyCode, KeyEvent event) 
	{ 
	if(keyCode==KeyEvent.KEYCODE_BACK) 
	{ 

	this.finish(); 
	return super.onKeyDown(keyCode, event); 

	} 
	return false; 
	}
	
	
	
	public boolean onMyKeyDown(int keyCode, KeyEvent event)
	{
		if (keyCode == KeyEvent.KEYCODE_I) {
			myMapView.getController().setZoom(myMapView.getZoomLevel() + 1);
			return true;
		} else if (keyCode == KeyEvent.KEYCODE_O) {
			myMapView.getController().setZoom(myMapView.getZoomLevel() - 1);
			return true;
		} else if (keyCode == KeyEvent.KEYCODE_S) {
			myMapView.setSatellite(true);
			return true;
		} else if (keyCode == KeyEvent.KEYCODE_M) {
			myMapView.setSatellite(false);
			return true;
		}
		return false;
	}
	
	public String getAddress()
	{
		String add=null;
		Geocoder geocoder = new Geocoder(getApplicationContext(), Locale.getDefault());
		 try {
			List<Address> addresses = geocoder.getFromLocation(
					 geoPoint.getLatitudeE6()  / 1E6, 
					 geoPoint.getLongitudeE6() / 1E6, 1);
		    
           if (addresses.size() > 0) 
           {
               for (int i=0; i<addresses.get(0).getMaxAddressLineIndex(); 
                    i++)
                  add += addresses.get(0).getAddressLine(i)+ " ";
           }
           
         //  Log.v("bishon:addressme-->", add);
           
           
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return add;
		
		
	}
	
	
	@Override
    public void onPause()
    {
    finish();
    super.onPause();
    }
    @Override
    public void onStop()
    {
    finish();
    super.onStop();
    }
    
	
	/* Class overload draw method which actually plot a marker,text etc. on Map */
	protected class MyLocationOverlay extends com.google.android.maps.Overlay {
		
		
		
		@Override
		public boolean draw(Canvas canvas, MapView mapView, boolean shadow, long when) {
			
			Paint paint = new Paint();
			
			super.draw(canvas, mapView, shadow);
			// Converts lat/lng-Point to OUR coordinates on the screen.
			Point myScreenCoords = new Point();
			mapView.getProjection().toPixels(geoPoint, myScreenCoords);
			
			paint.setStrokeWidth(1);
			paint.setARGB(255, 0, 0, 255);
			paint.setStyle(Paint.Style.STROKE);
			
			Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.marker);
			
			canvas.drawBitmap(bmp, myScreenCoords.x, myScreenCoords.y, paint);
			canvas.drawText("I am here...", myScreenCoords.x, myScreenCoords.y, paint);
			
			return true;
		}
	}

	
   
}
